// router/index.ts
import { createRouter, createWebHistory} from 'vue-router'
import Login from '@/components/Login.vue';
import NotFound from '@/components/NotFound.vue';
import Index from '@/components/Index.vue';
import Main from '@/components/Main.vue';
import { useGlobalStore } from '../store/userInfo';
import API from '../utils/api'
import { generateRoutes } from '../utils/dynamicRouter'
import { useTabStore } from '@/store/tabs'
import { ro } from 'element-plus/es/locales.mjs';

// 静态路由（所有人都能访问）
export const constantRoutes = [
  //首页路由
  {
    path: '/',
    name:'Main',
    component: Main,
    redirect: '/index',
    meta: {
      title: '首页',
      icon: 'dashboard'
    },
    children: [
      {
        path: '/index',
        name: 'Index',
        component: Index,
        meta: { title: '首页', icon: 'dashboard',notShowTab:true }
      },
    ]
  },
  {
    path: '/login',
    component: Login,
    meta: { hidden: true }
  },
  {
    path: '/404',
    component: NotFound,
    meta: { hidden: true }
  },
]

// 动态路由（根据权限加载）
export const asyncRoutes = [
      
]

const router = createRouter({
  history: createWebHistory(),
  routes: constantRoutes
})

// 重置路由（用于退出登录或切换账号时）
export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher
}

let isAddRouter = false;

//路由守卫
router.beforeEach(async (to, from, next) => {
  const globalData = useGlobalStore();
  if(to.path === '/login'){
    next();
  }else{
    let token =  globalData.token;
    if(!token){
      router.push('/login')
    }
    if(!isAddRouter){
      let dbMenu=globalData.menus;
      if(dbMenu.length==0){
        dbMenu = await API.getMenus();
        //存起来
        globalData.setMenus(dbMenu)
      }
      let dynamicRouter = generateRoutes(dbMenu);
     
      let newChildren = router.options.routes[0].children
      dynamicRouter.forEach(item => {
        //和首页平级,重新构造子路由
        newChildren.push(item)
      })
      newChildren.forEach(item => {
        if(!router.hasRoute(item.name)){
          router.addRoute('Main',item)
        }
      })
      isAddRouter = true;
      //防止页面白屏
      next({...to})
    }else{
      next()
    }
  }
})
// 每次跳转都记录/创建 tab 只创建后管固定的菜单
router.afterEach(to => {
  const tabStore = useTabStore()
  let list = routesToList(router.options.routes[0].children)
  list.forEach(item => {
    if(item === to.path){
      tabStore.addTab(to)
    }
  })
})

function routesToList(a,list=[]){
  a.forEach(item => {
    list.push(item.path)
    if(item.children && item.children.length > 0){
      routesToList(item.children,list)
    }
  })
  return list;
}

export default router